import 'dart:async';

import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/event_bus/global_event_bus.dart';
import 'package:star_author/event_bus/user_login_event.dart';
import 'package:star_author/utils/app_store_install_util.dart';
import 'package:star_author/utils/common_util/log_util.dart';
import 'package:star_author/utils/common_util/toast/custom_toast.dart';
import 'package:star_author/utils/http/api_manager.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/utils/user_util.dart';
import 'package:star_author/utils/validator.dart';
import 'package:star_author/widgets/checkbox.dart';
import 'package:star_author/widgets/empty_view/v_empty_view.dart';
import 'package:star_author/widgets/tap_transition_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
// import 'package:fluwx/fluwx.dart';
// import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:get/get.dart';
import 'package:package_info/package_info.dart';

import 'phone_login.dart';

class LoginPageHandler {
  Map getRequestMap(Map map) {
    Map resultMap = {
      ...map,
    };

    int storeChannelId = AppStoreInstallUtil.id;
    if (storeChannelId != -1) {
      resultMap['store_channel_id'] = storeChannelId;
    }

    LogUtil.v("LoginPage getPromoteUserMap $resultMap");
    return resultMap;
  }
}

class LoginPage extends StatefulWidget {
  static String routeName = '/LoginPage';

  final String jumpFrom;

  const LoginPage({
    Key? key,
    this.jumpFrom = '',
  }) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

final int seconds = 60;

class _LoginPageState extends State<LoginPage> {
  bool isChecked = false;
  bool availableBtn = false;
  bool waiting = false;

  int _start = seconds;
  Timer? _timer;
  final _mobileController = TextEditingController();
  final _codeController = TextEditingController();
  final _mobileNode = new FocusNode();
  final _codeNode = new FocusNode();

  void startStopWatch() {
    _timer = new Timer.periodic(new Duration(seconds: 1), (timer) {
      if (_start > 0) {
        update(() {
          availableBtn = false;
          _start--;
        });
      } else {
        timer.cancel();
        update(() {
          availableBtn = true;
          _start = seconds;
        });
      }
    });
  }

  bool get isTimeActive {
    return ![false, null].contains(_timer?.isActive);
  }

  get canFetchCode {
    return !isTimeActive && availableBtn && !waiting;
  }

  get messageButtonTextColor {
    return canFetchCode ? ColorConf.orange : ColorConf.highlightGray;
  }

  bool beforeLoginChecking() {
    if (!isChecked) {
      CustomToast.show("登录前请先勾选条款");
      return false;
    }
    return true;
  }

  String get getMessageButtonText {
    if (isTimeActive) {
      return '${_start}s重新获取';
    } else {
      return '获取验证码';
    }
  }

  bool isValidCode(code) {
    if ([null, ''].contains(code)) return false;

    return code.toString().length >= 4;
  }

  // StreamSubscription<BaseWeChatResponse>? streamSubscription; //绑定

  bool isShowWechatLogin = false;

  bool isInstallWx = false;

  @override
  void initState() {
    super.initState();

    // fluwx.isWeChatInstalled.then((value) {
    //   LogUtil.v('setVerifySDKInfo ${value}');
    //   isInstallWx = value;
    //   if (mounted) setState(() {});
    // });

    _mobileController.addListener(() {
      final String text = _mobileController.text;
      update(() {
        availableBtn = Validator.validMobile(text) == null;
      });
    });

    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      getIsShowWechat();
    });

    init();
  }

  void getIsShowWechat() async {
    ///update provider
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String version = packageInfo.version;
    HttpUtil.commonRequest(
      context,
      ApiManager.settings,
      queryParameters: {
        "app_version": version,
      },
      isLoading: false,
      isErrorToast: false,
    ).then((value) {
      bool auditingVersion = value.data["auditing_version"] ?? true;

      LogUtil.v('auditing_version$auditingVersion');

      ///为苹果设备，并且  auditing_version = true 才隐藏微信登陆按钮
      if (isInstallWx && !auditingVersion) {
        isShowWechatLogin = true;
      } else {
        isShowWechatLogin = false;
      }

      if (mounted) setState(() {});
    });
  }

  update(VoidCallback fn) {
    if (mounted) {
      setState(fn);
    }
  }

  bool isWeChatInstalled = false;

  init() async {
    // isWeChatInstalled = await fluwx.isWeChatInstalled; //苹果审核 没有安装app不能显示第三方登录
    //
    // update(() {});
    //
    // streamSubscription = fluwx.weChatResponseEventHandler.listen((res) async {
    //   streamSubscription?.cancel();
    //   if (res is fluwx.WeChatAuthResponse) {
    //     String? code = res.code;
    //     if (code == null) {
    //       CustomToast.show("微信授权失败");
    //     } else {
    //       try {
    //         if (res.errCode == 0) {
    //           final response = await HttpUtil.commonRequest(
    //             context,
    //             ApiManager.sessions_wechat_app,
    //             method: HttpUtil.MethodPost,
    //             data: LoginPageHandler().getRequestMap({"code": code}),
    //           );
    //
    //           if (response.statusCode == 201) {
    //             ///关闭页面
    //             Get.back();
    //
    //             String token = response.data['token'];
    //
    //             UserUtil.setToken(context, token);
    //
    //             UserUtil.tokenIsInvalid = true;
    //             GlobalEventBus().bus.fire(UserLoginEvent(true));
    //           } else {
    //             CustomToast.show("登录失败");
    //           }
    //         }
    //       } catch (e) {
    //         CustomToast.show("登录失败");
    //       }
    //     }
    //   }
    // });
  }

  onWeChatLogin() async {
    // bool isWechat = await fluwx.isWeChatInstalled;
    // if (!beforeLoginChecking()) return;
    // if (!isWechat) {
    //   CustomToast.show('没有安装微信，请安装后再使用微信登录');
    //   return;
    // }
    // await fluwx.sendWeChatAuth(
    //     scope: "snsapi_userinfo", state: "wechat_sdk_demo_test");
  }

  @override
  void dispose() {
    _timer?.cancel();
    _mobileController.dispose();
    _codeController.dispose();
    _mobileNode.dispose();
    _codeNode.dispose();
    // streamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          backgroundColor: Colors.white,
          body: Stack(
            children: [
              Container(
                height: Get.height,
                child: SafeArea(
                  child: GestureDetector(
                    onTap: () {
                      FocusManager.instance.primaryFocus?.unfocus();
                    },
                    child: Stack(
                      children: [
                        Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            buildTopWidget(),
                            buildContent(),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              Positioned(
                left: 0,
                right: 0,
                bottom: 30.w,
                child: buildFooter(),
              ),
            ],
          ),
        ),
        onWillPop: () async {
          GlobalEventBus().bus.fire(UserLoginEvent(false));
          return Future.value(true);
        });
  }

  Widget buildTopWidget() {
    return Column(
      children: [
        Container(
          width: double.infinity,
          height: 44.w,
          child: Align(
            alignment: Alignment(-0.93, 0.0),
            child: GestureDetector(
              child: Image(
                  image: AssetImage('images/lt_common/close_icon.png'),
                  width: 20.w,
                  height: 20.w),
              onTap: () {
                Get.back();
              },
            ),
          ),
        ),
        VEmptyView(50.w),
        Container(
          child: Column(
            children: [
              RoucesUtil.getAssetsIcon('ic_login_logo_lt', 96.w),
              SizedBox(
                height: 10.w,
              ),
              Image.asset(
                RoucesUtil.getAssets('ic_login_text'),
                width: 53.w,
                height: 28.w,
              ),
            ],
          ),
          alignment: Alignment.center,
        )
      ],
    );
  }

  buildContent() {
    return Container(
      margin: EdgeInsets.only(top: 160.w),
      padding: EdgeInsets.symmetric(horizontal: 35.w),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            children: [
              if (isShowWechatLogin)
                GestureDetector(
                  child: Container(
                    alignment: Alignment.center,
                    height: 46.w,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image(
                          image: AssetImage('images/ic_login_wechat.png'),
                          width: 32.w,
                          height: 27.w,
                        ),
                        SizedBox(
                          width: 10.w,
                        ),
                        Text(
                          '微信账号快捷登录',
                          style: TextStyle(
                              fontSize: 16.sp,
                              color: Colors.white,
                              fontWeight: FontWeight.w500),
                        )
                      ],
                    ),
                    decoration: BoxDecoration(
                        color: Color(0xFF44A949),
                        borderRadius: BorderRadius.circular(50)),
                  ),
                  onTap: () {
                    onWeChatLogin();
                  },
                  behavior: HitTestBehavior.opaque,
                ),
              GestureDetector(
                child: Container(
                  alignment: Alignment.center,
                  height: 46.w,
                  margin: EdgeInsets.only(top: 10),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        '手机号码登录/注册',
                        style: TextStyle(
                            fontSize: 14.sp,
                            color: Color(0xFF16385E),
                            fontWeight: FontWeight.w500),
                      )
                    ],
                  ),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(50)),
                ),
                onTap: () {
                  Get.off(PhoneLoginPage(
                    isShowWeChat: isShowWechatLogin,
                    jumpFrom: widget.jumpFrom,
                  ));
                },
                behavior: HitTestBehavior.opaque,
              )
            ],
          ),
        ],
      ),
    );
  }

  buildFooter() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        CheckboxWidget(
          onChanged: (val) {
            update(() {
              isChecked = val;
            });
          },
          select: isChecked,
        ),
        TapTransitionWidget(
          onPressed: () {
            update(() {
              isChecked = !isChecked;
            });
          },
          child: Text(
            '我已阅读并同意',
            style: TextStyle(
              fontSize: 12.sp,
              color: ColorConf.lightGray,
            ),
          ),
        ),
        TapTransitionWidget(
          onPressed: () {},
          child: Text(
            '《回流用户协议》',
            style: TextStyle(
              fontSize: 12.sp,
              color: ColorConf.blue,
            ),
          ),
        ),
        TapTransitionWidget(
          onPressed: () {},
          child: Text(
            '《回流隐私条款》',
            style: TextStyle(
              fontSize: 12.sp,
              color: ColorConf.blue,
            ),
          ),
        ),
      ],
    );
  }
}
